package thread;

/**
 * 演示多线程并发安全问题
 *
 * 模拟两个人来取钱
 */
public class SyncDemo1 {
    public static boolean success1=false;//表示1号线程是否取款成功，默认都是取款失败
    public static boolean success2=false;
    public static void main(String[] args) {
        Bank bank = new Bank();//银行实例化
        int sum=0;//是个while循环次数的计数器
        while(true) {
            sum++; //记录循环次数
            Thread t1 = new Thread() {
                public void run() {
                    success1 = bank.getMoney(20000);
                }
            };
            Thread t2 = new Thread() {
                public void run() {
                    success2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();

            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (success1 && success2) { //同时是true说明俩人都取款成功，这就出现了并发问题了
                System.out.println("问题出现，一共尝试了:" + sum + "次");
            } else {
                bank.saveAccount(20000); //存入20000等待下次同时取款实验
                success1 = false;
                success2 = false;//将两人的取款状态恢复到默认都是false
            }
        }
    }
}
